<?php

namespace app\wechat\command;

use app\wechat\model\MessageTemplate;
use app\wechat\model\OauthUser;
use EasyWeChat\Factory;
use Illuminate\Support\Collection;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\console\input\Argument;

class WechatCommand extends Command
{
    protected function configure()
    {
        $this->setName('wechat')->setDescription('用于与公众号交互');
        $this->addArgument('action', Argument::REQUIRED, '要执行的操作: menu push_message sync_template');
    }

    /**
     * APP
     *
     * @var \EasyWeChat\OfficialAccount\Application
     */
    private $app;
    /**
     * 初始化
     * @param Input  $input  An InputInterface instance
     * @param Output $output An OutputInterface instance
     */
    protected function initialize(Input $input, Output $output)
    {
        $this->app = Factory::officialAccount(config('wechat'));
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        switch ($action) {

            case 'menu':
                $this->menu();
                break;
            case 'push_message':
                $this->pushMessage();
                break;
            case 'sync_template':
                $this->syncTemplate();
                break;
            case 'sync_user':
                $this->syncUser();
                break;
            default:
                throw new \RuntimeException("不存在的执行命令 {$action}", 1);
        }
    }

    /**
     * 推送子菜单
     *
     * @return void
     */
    private function menu()
    {
        $buttons = [
            [
                "type" => 'view',
                "name" => '主页',
                'url'  => 'https://www.gzdcyl.com/'
            ],
            [
                "type" => 'view',
                "name" => '联系客服',
                'url'  => 'https://mk.deaigz.com/index/index/index'
            ],
            [
                "name" => '个人中心',
                // 'url'  => 'https://mk.deaigz.com/index/register/ok'
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "专属客服",
                        "url" => "https://mk.deaigz.com/index/serve/index"
                    ],
                ],
            ]
        ];

        $this->app->menu->delete();
        dump($this->app->menu->create($buttons));
    }

    private function pushMessage()
    {
        $this->app->template_message->send([
            'touser' => 'oKdEm668dTGQChIeI-Jo4kMzwoUY',
            'template_id' => 'GK_MTa5Xnx7oNflSttyFplCV4fpoJsVmDLFG56UUz-U',
            'url' => url('/', null, null, true),
            'data' => [
                'first' => '你好，接收到客户通知。',
                'keyword1' => 'MJ',
                'keyword2' => date('Y-m-d H:i:s'),
                'remark' => '请尽快上线答复客户',
            ],
        ]);
    }

    /**
     * 同步模板
     *
     * @return void
     */
    public function syncTemplate()
    {
        $template_list = $this->app->template_message->getPrivateTemplates()['template_list'] ?? [];
        if ($template_list) {
            $template_ids = array_column($template_list, 'template_id');
            /**
             * @var Collection
             */
            $templates = MessageTemplate::all();
            foreach ($template_list as $template_arr) {
                if ($template = $templates->firstWhere('template_id', $template_arr['template_id'])) {
                    $template->title = $template_arr['title'];
                    $template->primary_industry = $template_arr['primary_industry'];
                    $template->deputy_industry = $template_arr['deputy_industry'];
                    $template->content = $template_arr['content'];
                    $template->example = $template_arr['example'];
                    $template->deleted_at = null;
                } else {
                    $template = new MessageTemplate($template_arr);
                }
                $template->save();
            }
            //删除模板
            $templates->whereNotIn('template_id', $template_ids)->each(function ($template) {
                $template->deleted_at = date('Y-m-d H:i:s');
                $template->save();
            });
        }
    }

    /**
     * 同步用户
     *
     * @return void
     */
    private function syncUser()
    {
        $next_openid = null;
        while ($list = $this->app->user->list($next_openid)) {
            $next_openid = $list['next_openid'];
            if (!isset($list['data'])) break;
            $openids = $list['data']['openid'];
            $users = $this->app->user->select($openids);
            /**
             * @var \Illuminate\Support\Collection
             */
            $userModels = OauthUser::where('openid', 'in', $openids)->select();

            foreach ($users['user_info_list'] as $user) {
                $openid = $user['openid'];
                if ($userModel = $userModels->firstWhere('openid', $openid)) {
                    foreach ($user as $key => $value) {
                        if (isset($userModel->$key)) {
                            $userModel->$key = $value;
                        }
                    }
                } else {
                    $userModel = new OauthUser($user);
                    $userModel->allowField(true);
                }
                $userModel->save();
            }
        }
    }
}
